package com.ztools.pc.service.impl.store;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztools.common.model.pc.store.Supplier;
import com.ztools.common.util.common.PageUtil;
import com.ztools.pc.mapper.store.SupplierMapper;
import com.ztools.pc.service.store.SupplierService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:一口香菜
 * @Date: 2023/3/26  13:20
 * @Version 1.0
 */
@Transactional
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {


    @Override
    public Page<Supplier> findList(PageUtil<Supplier> pageUtil) {
        List<OrderItem> orders = new ArrayList<>();
        QueryWrapper<Supplier> queryWrapper = getQueryWrapper(pageUtil.getParams());
        Page<Supplier> pages = new Page<>(pageUtil.getPage(), pageUtil.getSize());
        // 排序数据  StrUtil.toUnderlineCase huTools将驼峰装换为下划线格式
        orders.add(new OrderItem(StrUtil.toUnderlineCase(pageUtil.getSortName()), "asc".equals(pageUtil.getSortOrder())));
        pages.setOrders(orders);
        return page(pages, queryWrapper);
    }

    @Override
    public boolean delete(Supplier supplier) {
        boolean b = false;
        Supplier userById = getById(supplier.getId());
        b = removeById(supplier.getId());
        return b;
    }

    @Override
    public boolean add(Supplier supplier) {
        return save(supplier);
    }

    @Override
    public boolean update(Supplier supplier) {
        boolean b = false;
        // 修改前先获取，在删除（乐观锁）
        Supplier categoryById = getById(supplier);
        b = updateById(supplier);
        return b;
    }


    /**
     * 拼装条件
     *
     * @param supplier supplier
     * @return Supplier
     */
    public QueryWrapper<Supplier> getQueryWrapper(Supplier supplier) {
        QueryWrapper<Supplier> gradeQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(supplier.getName())) {
            gradeQueryWrapper.like("name", supplier.getName());
        }
        return gradeQueryWrapper;
    }

}
